import { createRouter, createWebHashHistory } from 'vue-router'
import Login from '../views/login/Login.vue'
import Register from '../views/register/Register.vue'

const routes = [
  {
    path: '/',
    name: 'Home',
    // component: Home
    // 异步组件的方式加载，提高首页性能优化，
    component: () => import(/* webpackChunkName: home */'../views/home/Home.vue')
  }, {
    path: '/shop/:id',
    name: 'Shop',
    component: () => import(/* webpackChunkName: shop */'../views/shop/Shop.vue')
  },
  {
    path: '/login',
    name: 'Login',
    component: Login,
    // 只有你访问login之前才会执行,如果我已经登录就无法访问login页面
    beforeEnter (to, from, next) {
      // 先读取本地的值是否存在，如果存在就走到hone页面，如果不存在就跳转到登录页
      const isLogin = localStorage.isLogin
      if (isLogin) {
        next({ name: 'Home' })
      } else {
        next()
      }
    }
  },
  {
    path: '/register',
    name: 'Register',
    component: Register,
    beforeEnter (to, from, next) {
      const isLogin = localStorage.isLogin
      if (isLogin) {
        next({ name: 'Home' })
      } else {
        next()
      }
    }
  }
]

const router = createRouter({
  history: createWebHashHistory(),
  routes
})
// 路由切换都会执行
router.beforeEach((to, from, next) => {
  // const isLogin = localStorage.isLogin 这个代码跟上面一行是一样的
  const { isLogin } = localStorage
  const { name } = to
  // 如果是登录or注册页面就直接展示，展示的时候判断是登录状态还是注册状态
  const isLoginOrRegister = (name === 'Login' || name === 'Register');
  (isLogin || isLoginOrRegister)
    ? next()
    : next({ name: 'Login' })
})

export default router
